<script setup>
import { reactive, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import useUserStore from "@/pinia/modules/userStore";

const userStore = useUserStore();

/*登录后跳转的地址*/
const retuen_url = ref("");
/*登录后跳转的方式*/
const routerType = ref("");

/*表单组件实例*/
const formRef = ref(null);
/*表单数据对象*/
const formData = reactive({
  account: "tpq1103",
  password: "123456",
});
/*表单规则对象*/
const formRules = reactive({
  account: {
    rules: [
      { required: true, errorMessage: "请输入账号" },
      { pattern: "^[a-zA-Z0-9]{6,8}$", errorMessage: "账号格式不正确" },
    ],
  },
  password: {
    rules: [
      { required: true, errorMessage: "请输入密码" },
      { pattern: "^\\d{6}$", errorMessage: "密码格式不正确" },
    ],
  },
});
/*登录按钮的回调函数*/
const handleLogin = async () => {
  try {
    const validate = await formRef.value.validate().catch(error => error);
    if (validate instanceof Array) return;
    await userStore.accountLogin(formData);
    uni.showToast({ title: "登录成功", duration: 2000, icon: "success" });
    if (routerType.value) {
      uni[routerType.value]({
        url:retuen_url.value
      })
    } else {
      uni.switchTab({ url: "/pages/my/index" });
    }
  } catch (error) {
    uni.showToast({ title: error.message, duration: 2000, icon: "error" });
  }
};

onLoad((query) => {
  routerType.value = query.routerType;
  retuen_url.value = query.return_url;
});

</script>

<template>
  <uni-forms class="login-form" ref="formRef" err-show-type="toast" :model="formData" :rules="formRules">
    <uni-forms-item name="account">
      <input type="text" placeholder="请输入账号" class="uni-input-input" placeholder-style="color: #818181" v-model="formData.account" />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input type="password" placeholder="请输入密码" class="uni-input-input" placeholder-style="color: #818181" v-model="formData.password" />
    </uni-forms-item>
    <button class="submit-button" @tap="handleLogin">登录</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
@import './styles.scss';
</style>
